<template>
  <span v-html="label"/>
</template>
<script>
import Utils from '@/utils'
import fecha from '@/utils/date'
import { getData as getAreaData } from '@/api/platform/address'
import { getData as getDictionaryData } from '@/api/platform/dictionary'
import { getUserById } from '@/api/platform/org/employee'
import { getOrgById } from '@/api/platform/org/org'
import { getPositionById } from '@/api/platform/org/position'
import { getRoleById } from '@/api/platform/org/role'
import { getInfo as getAttachmentById } from '@/api/platform/attachment'

var WorldDistricts = null
getAreaData().then((response) => {
  WorldDistricts = response.data
})
var DICTIONARY_CACHE = {}
var ATTACHMENT_CACHE = {}
var SELECTOR_CACHE = {}
export default {
  props: {
    labelKey: {// 展示的字段
      type: String
    },
    data: {
      type: Object,
      default: () => {}
    },
    templateFields: {// 跟vee冲突
      type: Object,
      default: () => {}
    },
    defaultValue: {
      type: String,
      default: '&nbsp;'
    }
  },
  data() {
    return {
      label: ''
    }
  },
  watch: {
    data() {
      this.initData()
    },
    labelKey() {
      this.initData()
    }
  },
  mounted: function() {
    this.initData()
  },
  methods: {
    initData() {
      if (!this.labelKey) return
      const value = this.data[this.labelKey]
      if (this.$utils.isEmpty(value)) {
        this.label = this.defaultValue
        return
      }
      var field = this.templateFields[this.labelKey]
      if (!field) {
        this.label = value
        return
      }
      const fieldType = field.field_type
      const fieldOptions = field.field_options
      if (Utils.isEmpty(value) || Utils.isEmpty(fieldType) || Utils.isEmpty(fieldOptions)) {
        this.label = value
        return
      }

      // 数据格式
      this.dataFormatter(value, fieldType, fieldOptions)
    },
    dataFormatter(value, fieldType, fieldOptions) {
      if (fieldType === 'hidden' ||
          fieldType === 'text' ||
          fieldType === 'textarea' ||
          fieldType === 'editor' ||
          fieldType === 'autoNumber') {
        this.label = value
        return
      } else if (fieldType === 'number') { // TODO 数字
        this.label = value
        return
      } else if (fieldType === 'datePicker' ||
          fieldType === 'currentDate' ||
          fieldType === 'currentTime') { // 日期格式
        const format = fieldOptions['datefmt'] || 'yyyy-MM-dd HH:mm:ss'
        this.label = fecha.format(fecha.parse(value, format), format)
      } else if (fieldType === 'select' || fieldType === 'radio' || fieldType === 'checkbox') { // 下拉，单选，多选
        this.label = this.formatterOptions(value, fieldOptions['options'], 'val')
      } else if (fieldType === 'dictionary') { // 数据字典
        this.formatDictionary(fieldOptions['dictionary'], value)
      } else if (fieldType === 'customDialog') { // TODO 自定义对话框
        this.label = value
      } else if (fieldType === 'linkdata') { // TODO 关联数据
        this.label = value
      } else if (fieldType === 'selector') { // 选择器
        const store = fieldOptions['store'] || 'json'
        if (store === 'json') {
          this.label = this.formatterJson(value, 'name')
        } else if (store === 'id') {
          const selectorType = fieldOptions['selector_type']
          this.formatterSelectorData(selectorType, value)
        } else {
          this.label = value
        }
      } else if (fieldType === 'attachment') { // 附件
        const store = fieldOptions['store'] || 'json'
        if (store === 'json') {
          this.label = this.formatterJson(value, 'fileName')
        } else if (store === 'id') {
          this.formatterAttachmentData(value)
        } else if (store === 'path') { // TODO 暂时不处理
          this.formatterAttachmentData(value, store)
        }
        return value
      } else if (fieldType === 'address') { // 地址
        const store = fieldOptions['store'] || 'stringKey'
        if (store === 'stringKey') {
          var jsonValue = {}
          try {
            jsonValue = JSON.parse(value)
          } catch (e) {
            this.label = value
            return
          }
          if (Utils.isEmpty(jsonValue)) {
            this.label = value
            return
          }
          this.label = this.getAddressData(fieldOptions, jsonValue, 'country') +
              this.getAddressData(fieldOptions, jsonValue, 'province') +
              this.getAddressData(fieldOptions, jsonValue, 'city') +
              this.getAddressData(fieldOptions, jsonValue, 'district') +
                  (jsonValue.street ? jsonValue.street : '')
        }
      } else {
        this.label = value
      }
    },
    /**
     * 数据字典
     */
    formatDictionary(key, value) {
      if (DICTIONARY_CACHE[key]) {
        this.label = this.formatterOptions(value, DICTIONARY_CACHE[key], 'key', 'name')
      } else {
        getDictionaryData({
          type: key
        }).then(response => {
          const data = response.data
          DICTIONARY_CACHE[key] = data
          this.label = this.formatterOptions(value, data, 'key', 'name')
        }).catch((e) => {
          DICTIONARY_CACHE[key] = []
          // 异常
          console.error(e)
        })
      }
    },
    /**
     * 格式化选择器的数据
     */
    formatterSelectorData(type, id) {
      var key = type + ':' + id
      var nameKey = 'name'
      if (SELECTOR_CACHE[key]) {
        this.label = SELECTOR_CACHE[key]
      } else {
        if (type === 'user') {
          getUserById({ id: id }).then(response => {
            const data = response.data
            data[nameKey] = data['fullname']
            if (data) {
              SELECTOR_CACHE[key] = data[nameKey]
              this.label = data[nameKey]
            }
          }).catch((e) => {
            console.error(e)
          })
        } else if (type === 'org') {
          getOrgById({ id: id }).then(response => {
            const data = response.data
            if (data) {
              this.label = data[nameKey]
              SELECTOR_CACHE[key] = data[nameKey]
            }
          }).catch((e) => {
            console.error(e)
          })
        } else if (type === 'position') {
          getPositionById({ id: id }).then(response => {
            const data = response.data
            if (data) {
              this.label = data[nameKey]
              SELECTOR_CACHE[key] = data[nameKey]
            }
          }).catch((e) => {
            console.error(e)
          })
        } else if (type === 'role') {
          getRoleById({ id: id }).then(response => {
            const data = response.data
            if (data) {
              this.label = data[nameKey]
              SELECTOR_CACHE[key] = data[nameKey]
            }
          }).catch((e) => {
            console.error(e)
          })
        }
      }
    },
    /**
     * 附件
     */
    formatterAttachmentData(id, type = 'id') {
      if (ATTACHMENT_CACHE[id]) {
        this.label = ATTACHMENT_CACHE[id]
      } else {
        getAttachmentById({ id: id, type: type }).then(response => {
          const data = response.data
          this.label = data['fileName']
          ATTACHMENT_CACHE[id] = data['fileName']
        }).catch((e) => {
          console.error(e)
        })
      }
    },
    // ====================地址展示处理================
    getTextValue: function(data, value) {
      if (Utils.isEmpty(value) || Utils.isEmpty(data)) { return value || '' }
      if (data[value]) {
        return data[value]
      }
      return value || ''
    },
    getTop: function(fieldOptions) {
      return 	fieldOptions['top'] ? fieldOptions['top'] : 'country'
    },
    getLevel: function(fieldOptions) {
      return fieldOptions['level'] ? fieldOptions['level'] : 'district'
    },
    getTopval: function(fieldOptions) {
      var top = this.getTop(fieldOptions)
      var rtnVal = '0'
      var topval = fieldOptions['topval']
      if (Utils.isEmpty(topval)) { return rtnVal }
      if (top === 'province') {
        rtnVal = topval['country']
      } else if (top === 'city') {
        rtnVal = topval['province']
      } else if (top === 'district') {
        rtnVal = topval['city']
      }
      return rtnVal
    },
    getAddressData(fieldOptions, v, type) {
      if (Utils.isEmpty(v)) { return '' }
      var top = this.getTop(fieldOptions)
      var topval = this.getTopval(fieldOptions)
      var topval1
      if (type === 'country' && v.country) {
        topval = (top === 'country') ? topval : 0
        if (Utils.isEmpty(topval)) { return '' }
        return this.getTextValue(WorldDistricts[topval],
          v.country)
      } else if (type === 'province' && v.province) {
        topval1 = Utils.isNotEmpty(v.country) ? v.country : null
        if (Utils.isEmpty(topval1) && top === 'province') { topval1 = topval }
        if (Utils.isEmpty(topval1)) { return '' }
        return this.getTextValue(WorldDistricts[topval1],
          v.province)
      } else if (type === 'city' && v.city) {
        topval1 = Utils.isNotEmpty(v.province) ? v.province : null
        if (Utils.isEmpty(topval1) && top === 'city') { topval1 = topval }
        if (Utils.isEmpty(topval1)) { return '' }
        return WorldDistricts[topval1] ? (WorldDistricts[topval1][v.city] || '')
          : ''
      } else if (type === 'district' && v.district) {
        topval1 = Utils.isNotEmpty(v.city) ? v.city : null
        if (Utils.isEmpty(topval1) && top === 'district') { topval1 = topval }
        if (Utils.isEmpty(topval1)) { return '' }
        return WorldDistricts[topval1] ? (WorldDistricts[topval1][v.district] || '') : ''
      } else {
        return ''
      }
    },
    // ====================地址展示处理END================

    formatterOptions(value, options, valueKey = 'value', labelKey = 'label') {
      const optionObj = {}
      options.map(option => {
        optionObj[option[valueKey]] = option[labelKey]
      })
      const aryValue = value.split(',')
      const res = aryValue.map((v) => {
        return optionObj[v] || v
      })
      return res.join(' ')
    },
    /**
   * 格式json 数据
   */
    formatterJson(value, key) {
      let aryValue = []
      try {
        aryValue = JSON.parse(value)
      } catch (e) {
        return value
      }
      if (Utils.isEmpty(aryValue)) { return '' }

      const res = aryValue.map((val) => {
        return val[key]
      })
      return res.join(' ')
    }

  }
}
</script>
